﻿using System;
using System.Collections.Generic;
using System.Linq;
using InterpriseSuiteEcommerceCommon.DataAccess;
using InterpriseSuiteEcommerceCommon.Extensions;
using InterpriseSuiteEcommerceCommon.DTO;

namespace InterpriseSuiteEcommerceCommon
{
    public static class RegistryCustomerExtension
    {
        public static void AddToDb(this IEnumerable<GiftRegistry> giftRegistries, GiftRegistry giftRegistry)
        {
            if (giftRegistry == null) return;
            GiftRegistryDA.SaveGiftRegistry(giftRegistry);
        }

        public static void UpdateToDb(this IEnumerable<GiftRegistry> giftRegistries, GiftRegistry giftRegistry)
        {
            if (giftRegistry == null) return;
            GiftRegistryDA.UpdateGiftRegistry(giftRegistry);
        }

        public static GiftRegistry FindFromDb(this IEnumerable<GiftRegistry> giftRegistries, Guid registryID)
        {
            return GiftRegistryDA.GetGiftRegistryByRegistryID(registryID, InterpriseHelper.ConfigInstance.WebSiteCode);
        }

        public static void AddToDb(this IEnumerable<GiftRegistryItem> items, GiftRegistryItem giftRegistryItem)
        {
            GiftRegistryDA.AddGiftRegistryItems(giftRegistryItem);
        }

        public static void AddToDb(this IEnumerable<GiftRegistryItem> items, IEnumerable<GiftRegistryItem> giftRegistryItems)
        {
            giftRegistryItems.ForEach<GiftRegistryItem>(item =>
            {
                if (item.RegistryItemCode == null) item.RegistryItemCode = Guid.NewGuid();
                GiftRegistryDA.AddGiftRegistryItems(item);
            });
        }

        public static void UpdateToDb(this IEnumerable<GiftRegistryItem> items, GiftRegistryItem giftRegistryItem)
        {
            GiftRegistryDA.UpdateRegistryItem(giftRegistryItem);
        }

        public static IEnumerable<GiftRegistryItem> BuildItemsForTransaction(this IEnumerable<GiftRegistryItem> items, Customer thisCustomer, Guid giftRegistryID)
        {
            foreach (var item in items)
            {
                string itemCode = item.ItemCode;

                bool withVat = AppLogic.AppConfigBool("VAT.Enabled") && thisCustomer.VATSettingReconciled == VatDefaultSetting.Inclusive;
                UnitMeasureInfo um = UnitMeasureInfo.ForItem(item.ItemCode, UnitMeasureInfo.ITEM_DEFAULT);

                var eCommerceProductInfoView = AppLogic.GetProductInfoViewForShowProduct(DB.SQuote(itemCode),
                                                    DB.SQuote(thisCustomer.LocaleSetting),
                                                    DB.SQuote(InterpriseHelper.ConfigInstance.UserCode),
                                                    DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                                                    DB.SQuote(Localization.DateTimeStringForDB(DateTime.Now)),
                                                    DB.SQuote(thisCustomer.ProductFilterID),
                                                    DB.SQuote(thisCustomer.ContactCode));

                decimal promotionalPrice = decimal.Zero;
                decimal price = 0;
                if (!eCommerceProductInfoView.IsAKit.HasValue || eCommerceProductInfoView.IsAKit.Value == 0)
                {
                    //remove the vat since this is just a registry
                    price = InterpriseHelper.GetSalesPriceAndTax(thisCustomer.CustomerCode,
                                                                itemCode,
                                                                thisCustomer.CurrencyCode,
                                                                decimal.One,
                                                                um.Code,
                                                                false,
                                                                ref promotionalPrice);
                }
                else //kit
                {
                    var kit = KitItemData.GetKitCompositionForGiftRegistry(thisCustomer, eCommerceProductInfoView.Counter, itemCode, item.RegistryID, item.RegistryItemCode);
                    string composition = string.Empty;

                    foreach (var grp in kit.Groups)
                    {
                        var selectedItems = grp.Items.Where(selItem => selItem.IsSelected);

                        price += selectedItems.Sum(selItem => selItem.UnitMeasures.FirstOrDefault(m => m.code == um.Code).price);

                        selectedItems.ForEach(i => { composition += string.Format("{0}+{1},", grp.Id, i.Id); });
                    }

                    if (!composition.IsNullOrEmptyTrimmed()) item.KitComposition = composition.Remove(composition.Length - 1, 1);
                }

                item.ProductPriceFormatted = InterpriseHelper.FormatCurrencyForCustomer(price, thisCustomer.CurrencyCode);
                item.ProductPrice = price;

                string actualSEName = eCommerceProductInfoView.ItemDescription.ToMungeName().ToUrlEncode().ToSubString(90);
                if (string.IsNullOrEmpty(actualSEName))
                {
                    actualSEName = eCommerceProductInfoView.ItemName.ToMungeName().ToUrlEncode().ToSubString(90);
                }

                string itemDescription = XmlCommon.GetLocaleEntry(eCommerceProductInfoView.ItemDescription, thisCustomer.LocaleSetting, true);
                if (string.IsNullOrEmpty(itemDescription))
                {
                    itemDescription = eCommerceProductInfoView.ItemName;
                }

                item.ProductCounter = eCommerceProductInfoView.Counter;
                item.ProductName = itemDescription.ToHtmlEncode();
                item.ProductURL = SE.MakeProductLink(eCommerceProductInfoView.Counter.ToString(), actualSEName);

                var img = ProductImage.Locate("product", itemCode, "large");
                item.ProductPhotoPath = img.src;
            }

            return items;
        }

        public static IEnumerable<KitItemFromComposition> GetKitItemsFromComposition(this GiftRegistryItem item)
        {
            if (!item.IsKit) return null;
            return GiftRegistryDA.GetKitItemsFromComposition(item.RegistryID, item.RegistryItemCode);
        }

        public static void ClearKitItemsFromComposition(this GiftRegistryItem item)
        {
            GiftRegistryDA.ClearKitItemsFromComposition(item.RegistryID, item.RegistryItemCode);
        }

        public static bool IsRegistryPrefixExist(this GiftRegistry giftregistry)
        {
            if (giftregistry.IsEditMode)
                return GiftRegistryDA.IsRegistryPrefixExist(giftregistry.RegistryID, giftregistry.CustomURLPostfix);
            else
                return GiftRegistryDA.IsRegistryPrefixExist(null, giftregistry.CustomURLPostfix);
        }

        public static bool IsRegistryOwnedByCustomer(this Customer customer, Guid registryId)
        {
            return customer.GiftRegistries.Any(reg => reg.RegistryID == registryId);
        }

        public static string GenerateRandomCustomURLForGiftRegistry(this Customer customer)
        {
            return customer.FirstName.Trim().Replace(" ", String.Empty) + customer.LastName.Trim().Replace(" ", String.Empty);
        }
    }
}
